//建立一个静态类 用于通过反射获取对应的数据库字段信息
using System;
using System.Reflection;

public static class AttributeProcess
{

    public static string GetTableName(Type type)
    {
        string tableName = string.Empty;
        //获取非继承的
        object[] attributes = type.GetCustomAttributes(false);
        foreach (var attr in attributes)
        {
            if (attr is TableAttribute)
            {
                TableAttribute tableAttribute = attr as TableAttribute;
                tableName = tableAttribute.Value;
            }
        }
        if (string.IsNullOrEmpty(tableName))
        {
            tableName = type.Name;
        }
        return tableName;
    }

    public static string GetColumnName(PropertyInfo  propertyInfo)
    {
        string columnName = string.Empty;
        object[] attributes = propertyInfo.GetCustomAttributes(false);
        foreach (var attr in attributes)
        {
            if (attr is ColumnAttribute)
            {
                ColumnAttribute columnAttribute = attr as ColumnAttribute;
                columnName = columnAttribute.Value;
            }
        }
        if (string.IsNullOrEmpty(columnName))
        {
            columnName = propertyInfo.Name;
        }
        return columnName;

    }

    //判断主键是否自增
    public static bool IsIncrement(Type type)
    {
            object[] attributes = type.GetCustomAttributes(false);
            foreach(var attr in attributes)
            {
                if(attr is PrimaryKeyAttribute)
                {
                    PrimaryKeyAttribute primaryKeyAttribute = attr as PrimaryKeyAttribute;
                    return primaryKeyAttribute.autoIncrement;
                }

            }
            return false;


    }

    //获取主键的列明
    public static string GetPrimaryKey(Type type)
    {
         string primaryKeyName = string.Empty;
         object[] attributes = type.GetCustomAttributes(false);
         foreach(var attr in attributes)
         {
             if(attr is PrimaryKeyAttribute)
             {
                 PrimaryKeyAttribute primaryKeyAttribute = attr as PrimaryKeyAttribute;
                 primaryKeyName = primaryKeyAttribute.Value;
             }
         }
         return primaryKeyName;

    }

    public static bool IsPrimaryKey(Type type,PropertyInfo property)
    {
            string primaryKey = GetPrimaryKey(type);
            string columnName = GetColumnName(property);
            return primaryKey==columnName;

    }
}